package main

import (
	"flag"
	"fmt"
	"image"
	"image/color"
	"image/draw"
	"log"

	"gitee.com/xuender/images"
)

func usage() {
	fmt.Fprintln(flag.CommandLine.Output(), "Usage of match: 图像匹配")
	fmt.Fprintln(flag.CommandLine.Output(), "\tmatch 目标图片 模板图片 [标识图片]")

	flag.PrintDefaults()
}

func main() {
	argLen := 2
	size := flag.Int("s", 3, "匹配数量.")
	distance := flag.Int("d", 0, "相似距离最大值.")
	ratio := flag.Int("r", 5, "模糊搜索距离系数，越大步长越小")
	fuzzy := flag.Int("f", 3, "模糊搜索命中数量和匹配数量的关系")

	flag.CommandLine.Usage = usage
	flag.Parse()

	if flag.NArg() < argLen {
		usage()
		log.Fatal("缺少参数")
	}

	target, err := images.Decode(flag.Arg(0))
	if err != nil {
		log.Fatal(flag.Arg(0), err)
	}

	template, err := images.Decode(flag.Arg(1))
	if err != nil {
		log.Fatal(flag.Arg(1), err)
	}

	log.Printf("开始识别图片 [ %s ] 中的 [ %s ]\n", flag.Arg(0), flag.Arg(1))

	m, err := images.NewMatch(target, template)
	if err != nil {
		log.Fatal(err)
	}

	m.Ratio = *ratio
	m.Size = *size
	m.Distance = *distance
	m.FuzzySize = *fuzzy

	ds, err := m.Match()
	if err != nil {
		log.Fatal(err)
	}

	if len(ds) == 0 {
		log.Fatal("未找到匹配区域")
	}

	log.Printf("找到匹配: %d 处\n", len(ds))

	for _, d := range ds {
		log.Printf("坐标: %d,%d,\t差距: %d\n", d.X, d.Y, d.Distance)
		images.Rect(
			target.(draw.Image),
			image.Rect(d.X, d.Y, d.X+template.Bounds().Dx(), d.Y+template.Bounds().Dy()),
			color.RGBA{255, 0, 0, 255},
		)
	}

	if flag.NArg() > argLen {
		save(target, flag.Arg(argLen))
	}
}

func save(target image.Image, file string) {
	if err := images.Save(target, file); err != nil {
		log.Fatal(err)
	}

	log.Println("保存图片: ", file)
}
